import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';
import 'package:provider/provider.dart';

import '../../hj_utils/api_service/mine_service.dart';
import '../../hj_utils/screen.dart';
import '../../routers/jump_router.dart';
import '../../tools_base/loading/l_error_widget.dart';
import '../../tools_base/loading/loading_center_widget.dart';
import '../mine_business/mine_vip/vip_support_model.dart';
import 'pre_sale_alert.dart';
import 'pre_sale_model.dart';
import 'pre_sale_provider.dart';

class PreSalePage extends StatefulWidget {
  static const routeName = '/presale';
  const PreSalePage({super.key});

  @override
  State<PreSalePage> createState() => _PreSalePageState();
}

class _PreSalePageState extends State<PreSalePage> {
  VipSupportModel? pageData;

  bool isLoading = true;

  VipProductListModel? selectProductM;

  VipProductModel? selectVipItem;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      PreSaleProvider().refreshPreSaleConfig();

      MineService.getVipProductInfo().then((value) {
        pageData = value;
        isLoading = false;
        pageData?.list?.forEach((e) {
          if (e.position == '预售卡') {
            selectProductM = e;
            selectVipItem = selectProductM?.list?.firstOrNull;
          }
        });
        setState(() {});
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      body: () {
        if (isLoading) return LoadingCenterWidget();
        if (pageData == null) return CErrorWidget();
        return Consumer<PreSaleProvider>(
          builder: (ctx, value, child) => Stack(
            children: [
              SingleChildScrollView(
                child: Column(
                  children: [
                    Stack(
                      children: [
                        NetworkImageLoader(
                          imageUrl: PreSaleProvider().advancePage?.pageBackground ?? '',
                          fit: BoxFit.fill,
                          width: double.infinity,
                          borderRadius: 0,
                          height: 1970,
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 0, vertical: 20),
                          child: Column(
                            children: [
                              SizedBox(height: 1116),
                              Stack(children: [
                                NetworkImageLoader(
                                  imageUrl: PreSaleProvider().advancePage?.pageVidBackground ?? ' ',
                                  width: double.infinity,
                                  height: 750,
                                  fit: BoxFit.fill,
                                ),
                                Positioned(
                                  child: GridView.builder(
                                      padding: EdgeInsets.only(left: 20, right: 20, top: 50),
                                      shrinkWrap: true,
                                      physics: NeverScrollableScrollPhysics(),
                                      itemCount: PreSaleProvider().preSaleModel?.list?.length ?? 0,
                                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                        crossAxisCount: 2, //横向数量
                                        crossAxisSpacing: 5, //间距
                                        mainAxisSpacing: 12, //行距
                                        childAspectRatio: 165 / 152,
                                      ),
                                      itemBuilder: (context, index) {
                                        return _buildVideoItem(PreSaleProvider().preSaleModel?.list?[index]);
                                      }),
                                  top: 55,
                                  left: 0,
                                  right: 0,
                                  bottom: 18,
                                )
                              ]),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Positioned(
                bottom: 37,
                left: 0,
                right: 0,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 44),
                  height: 46,
                  child: PreSaleActivityButton(
                    onTap: _onInitiatePayAction,
                  ),
                ),
              ),
              Positioned(
                child: InkWell(
                  onTap: () => Get.back(),
                  child: Icon(
                    Icons.arrow_back_ios_sharp,
                    size: 18,
                    color: Colors.white,
                  ),
                ),
                left: 16,
                top: screen.paddingTop + 20,
              )
            ],
          ),
        );
      }(),
    );
  }

  _onInitiatePayAction() {
    if (selectProductM == null && selectVipItem == null) {
      return;
    }
    PreSaleProvider().onInitiatePayAction(selectVipItem!..isPreSale = true);
  }

  Widget _buildVideoItem(PreSaleVideoModel? videoModel) {
    return InkWell(
      onTap: () => pushToVideoPage(videoId: videoModel?.vidId),
      child: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Positioned(
              left: 0,
              right: 0,
              top: 10,
              bottom: 0,
              child: Container(
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
              ),
            ),
            Positioned.fill(
                child: Column(
              children: [
                Expanded(
                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 3.5),
                    padding: EdgeInsets.all(4),
                    decoration: BoxDecoration(
                        boxShadow: [BoxShadow(color: Color(0xffD43824).withOpacity(.2), blurRadius: 2)],
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8)),
                    child: NetworkImageLoader(
                      imageUrl: videoModel?.cover ?? '',
                      width: null,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 15,
                    vertical: 3,
                  ),
                  child: Text("${videoModel?.vidTitle}",
                      style: const TextStyle(
                        color: Color(0xffDA0101),
                        fontWeight: FontWeight.w500,
                        fontSize: 12,
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1),
                ),
                Container(
                  height: 25,
                  margin: EdgeInsets.symmetric(horizontal: 16),
                  decoration: BoxDecoration(
                      boxShadow: [BoxShadow(color: Color(0xffD43824).withOpacity(.2), blurRadius: 2)],
                      gradient: LinearGradient(
                          colors: [Color(0xffFFF7E9), Color(0xffF9DC9A)], begin: Alignment.topLeft, end: Alignment.bottomRight),
                      borderRadius: BorderRadius.circular(12.5)),
                  padding: EdgeInsets.all(2),
                  child: Row(
                    children: [
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        '免费',
                        style: TextStyle(color: Color(0xffDA0101), fontSize: 14, fontWeight: FontWeight.w600),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                                  colors: [Color(0xffFFF3D9), Colors.white], begin: Alignment.topCenter, end: Alignment.bottomCenter),
                              borderRadius: BorderRadius.circular(12.5)),
                          alignment: Alignment.center,
                          child: Text(
                            "原价 ${videoModel?.coins}",
                            style: const TextStyle(
                              color: const Color(0xff8B8B8B),
                              fontSize: 12.0,
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 6.8)
              ],
            ))
          ],
        ),
      ),
    );
  }
}
